import createHandles from '@/handles/handle-list/create';
const bypass = (res) => res;
const noop = () => {};
const pipelines = {};

// summary: 对外提供的open api
// 1. 提供节点动作、协同相关动作、表单接口代理，第三方扩展的事件系统
// 2. TODO: 单独打包为sdk.js在页面环境变量下方最优先引入，加载时机 env.js - sdk.js - third-extension.js - app.js

const sdk = {
  _: {
    emitEvent(name, params) {
      return sdk._.emitPipe(name, params);
    },
    emitPipe(name, params) {
      let promise = Promise.resolve(params);
      let pipes = pipelines[name];
      pipes = pipes ? pipes.slice(0) : [];
      while (pipes.length) {
        const pipe = pipes.shift();
        promise.catch(pipe.rejected);
        promise = promise.then((input) => pipe.resolved(input, params));
      }
      return promise;
    }
  },
  pipe(name, proc) {
    if (!pipelines[name]) pipelines[name] = [];
    const pipes = pipelines[name];
    let { success, error, priority } = proc;
    priority = typeof priority === 'number' ? priority : 20;
    priority = Math.min(priority, 10e10);
    priority = Math.max(priority, -10e10);
    const pipe = {
      priority: priority,
      resolved: success || bypass,
      rejected: error || noop
    };
    let appended = false;
    for (let i = 0, l = pipes.length; i < l; ++i) {
      let current = pipes[i];
      if (current.priority < pipe.priority) {
        pipes.splice(i, 0, pipe);
        appended = true;
        break;
      }
    }
    if (!appended) {
      pipes.push(pipe);
    }
    return function () {
      for (let i = 0, l = pipes.length; i < l; ++i) {
        if (pipes[i] === pipe) {
          return pipes.splice(i, 1);
        }
      }
    };
  },
  on(name, func) {
    return sdk.pipe(name, {
      success(pipeParams, initParams) {
        return new Promise((resolve) => resolve(func(initParams))).catch((err) =>
          console.error(err)
        );
      }
    });
  },
  addNode() {
    createHandles.addNode();
  },
  preSubmit() {
    createHandles.preSubmit();
  }
};

// usage
// 事件
// SY.collab.on('click', function() {
//   console.log(1, performance.now());
// })
// SY.collab.on('click', function() {
//   console.log(2, performance.now());
//   throw 123;
// })
// SY.collab.on('click', function() {
//   console.log(3, performance.now());
// })
// sdk._.emitEvent('click', {t: 1111})
// 管道
// SY.collab.pipe('my-pipe', {
//   priority: 1000,
//   success: function (pipeParam, initParam) {
//       console.log([1000, pipeParam]);
//       return pipeParam + '-->1000';
//   }
// })
// SY.collab.pipe('my-pipe', {
//   priority: 1,
//   success: function (pipeParam, initParam) {
//       console.log([1, pipeParam]);
//   },
//   error: function(err) {
//       console.error(err);
//   }
// })
// SY.collab.pipe('my-pipe', {
//   priority: 100,
//   success: function (pipeParam, initParam) {
//       console.log([100, pipeParam])
//       throw 'unknow error'
//       return pipeParam + '-->100';
//   }
// })

export { sdk as sdk };
export default {
  init() {
    const SY = (window.SY = window.SY || {});
    if (SY.collab) {
      console.info('SY.collab is already initialized!');
      return;
    }
    SY.collab = SY.collab || sdk;
    window.$ = window.$ || {};
    window.$.ctp = window.$.ctp || {};
    // window.$.ctp.bind = (eventName, callback) => {
    //   sdk.on(eventName, callback);
    // };
    // window.$.ctp.trigger = (eventName, params) => {
    //   // TODO: 这里通过参数适配原始的API
    //   sdk._.emitEvent(eventName, params);
    // };
  }
};
